﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CalligraphyWeb.Models;
using Calligraphy.Models;
using Newtonsoft.Json;
using System.Web.Services;
using System.Drawing;
using ThuPhap.Class;
using WebMatrix.WebData;
using CalligraphyWeb.Filters;
using System.Net;

namespace CalligraphyWeb.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class EditorController : Controller
    {
        //
        // GET: /Editor/

        public ActionResult Index()
        {
            EditorModel model = new EditorModel();
            model.FontFamilies = Calligraphy.Models.FontFamily.Get();
            model.FontFamiliesList = Calligraphy.Models.FontFamily.GetSelectListItems();
            

            return View(model);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [HttpPost]
        public string InitializeJSON(EditorQueryData query)
        {
            string backgroundUrl = "/Data/Backgrounds/";
            string thumbnailUrl = "/Data/ItemImages/";
            string templateBackgroundUrl = "/Data/TemplateBackgrounds/"; 
            string TemplateImageUrl ="/Data/TemplateImages/"; 
            string galleriesUrl = "/Data/Galleries/";

            EditorModel model = new EditorModel();
            var userid = WebSecurity.GetUserId(User.Identity.Name);
            model.Galleries = Gallery.Search(author: userid);
            model.CommonGalleries = Gallery.Search(author: 3);
            model.Templates = Template.Search(author: userid);
            model.Items = Item.Search(author: userid);

            if (query.id > 0)
            {
                switch (query.type)
                {
                    case "template":
                        model.Item = new Template(query.id, false).ToItem();
                        model.TemplateID = query.id;
                            break;
                    case "project":
                    default:
                            model.Item = new Item(query.id, false).Data;
                        break;
                }

                model.Item.background = backgroundUrl + model.Item.background;
                

            }
            

            return JsonConvert.SerializeObject(model, Formatting.Indented,
                new JsonSerializerSettings
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                });

        }

        [AcceptVerbs(HttpVerbs.Post)]
        [HttpPost]
        public string SaveItem(SaveItemModel obj)
        {
           string galleriesDir = HttpRuntime.AppDomainAppPath + "Data\\Galleries\\";
           string bgDir = HttpRuntime.AppDomainAppPath + "Data\\Backgrounds\\";
            
            var temp = new Item(obj.Item);
            Image background = null;
            if (temp.Data.background.Length > 0)
                temp.Data.background = temp.Data.background.Split('/').LastOrDefault();

            //copy images
            if (System.IO.File.Exists(galleriesDir + temp.Data.background))
            {
                background = Image.FromFile(galleriesDir + temp.Data.background); //background
            }
            string backgroundPath = "";
            temp.Data.width = 480;
            temp.Data.height = 800;
            if (background != null)
            {
                backgroundPath = bgDir + temp.Data.background;
                if (!System.IO.File.Exists(backgroundPath))
                    background.Save(backgroundPath);
                temp.Data.width = background.Width;
                temp.Data.height = background.Height;
            }

            temp.Data.x = 0;
            temp.Data.y = 0;
            temp.Data.userid = WebSecurity.GetUserId(User.Identity.Name);
            temp.Data.status = "active";
            string previewName = ExportImage.Export(temp.Data);
            temp.Data.preview = previewName;

            foreach (var iter in temp.Data.itemControls)
            {
                iter.width =  iter.width / obj.Ratio;
                iter.height = iter.height / obj.Ratio ;
                iter.C_left = iter.C_left / obj.Ratio;
                iter.C_top = iter.C_top / obj.Ratio;
            }
            return temp.Save().ToString();
            
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [HttpPost]
        public int SaveTemplate(SaveTemplateModel obj)
        {
            var project = new Item(obj.Item);

            if (project.Data.background.Length > 0)
                project.Data.background = project.Data.background.Split('/').LastOrDefault();
            project.Data.userid = WebSecurity.GetUserId(User.Identity.Name);

            var template = project.ToTemplateInterface(obj.name, obj.description);
            if (obj.id > 0) template.Data.id = obj.id;

            foreach (var iter in template.Data.templateControls)
            {
                iter.width = iter.width / obj.Ratio;
                iter.height = iter.height / obj.Ratio;
                iter.C_left = iter.C_left / obj.Ratio;
                iter.C_top = iter.C_top / obj.Ratio;
            }

            return template.Save();

        }

        [AcceptVerbs(HttpVerbs.Post)]
        [HttpPost]
        public string ExportImg(SaveItemModel obj)
        {
            string thumbnailUrl = "/Data/ItemImages/";

            foreach (var iter in obj.Item.itemControls)
            {
                iter.width = iter.width / obj.Ratio;
                iter.height = iter.height / obj.Ratio;
                iter.C_left = iter.C_left / obj.Ratio;
                iter.C_top = iter.C_top / obj.Ratio;
            }

            var filename = ExportImage.Export(obj.Item);

            return thumbnailUrl + filename;
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [HttpPost]
        public string UploadImage(string url)
        {
            var userid = WebSecurity.CurrentUserId;
            string galleriesDir = HttpRuntime.AppDomainAppPath + "Data\\Galleries\\";
            WebClient webClient = new WebClient();
            var result = new DownloadImageResult();
            var filename = url.Split('/').Last();
            string galleriesUrl = "/Data/Galleries/";

            var uri = new Uri(url, UriKind.Absolute);

            webClient.DownloadFile(uri, galleriesDir + filename);
            result.Status = 1;
                result.Gallery =  new gallery() { name = filename.Split('.').First(),
                    status = "active",
                    url = galleriesUrl + filename,
                    image = filename,
                    userid = userid
                };
            var Gallery = new Gallery(result.Gallery);
            Gallery.Save();
            
            return JsonConvert.SerializeObject(result);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [HttpPost]
        public string UploadImageFromComputer(HttpPostedFileBase file)
        {
            var userid = WebSecurity.CurrentUserId;
            string galleriesDir = HttpRuntime.AppDomainAppPath + "Data\\Galleries\\";
            string galleriesUrl = "/Data/Galleries/";
            var result = new DownloadImageResult();

            // Verify that the user selected a file
            if (file != null && file.ContentLength > 0)
            {
                // extract only the fielname
                var fileName = Path.GetFileName(file.FileName);
                // store the file inside ~/App_Data/uploads folder
                var path = galleriesDir + fileName;
                file.SaveAs(path);
                result.Status = 1;
                result.Gallery = new gallery()
                {
                    name = fileName.Split('.').First(),
                    status = "active",
                    url = galleriesUrl + fileName,
                    image = fileName,
                    userid = userid
                };
                var Gallery = new Gallery(result.Gallery);
                Gallery.Save();
            }
            
            return JsonConvert.SerializeObject(result);
        }

    }
}
